package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.JwtClaimsConstant;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Objects;


/**
 * UserServiceImpl
 *
 * @author liliudong
 * @version 1.0
 * @description UserService
 * @date 2023/8/1 10:49
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public UserLoginVO login(String code) {
        // 1. 把code发给微信服务器，校验，取openid
        HashMap<String, String> params = new HashMap<>(8);
        params.put("appid", weChatProperties.getAppid());
        params.put("secret", weChatProperties.getSecret());
        params.put("js_code", code);
        params.put("grant_type", "authorization_code");
        String json = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", params);
        // {"session_key":"LES79z3O\/MgGEV+OZwFQ6w==","openid":"osvjO5cWLOml-UKudDPvJCyjimMk","unionid":"o5PB1s4dW71sXhxQg0ZH776q_zM8"}
        log.info("响应结果: {}", json);
        JSONObject jsonObject = JSON.parseObject(json);

        String openid = jsonObject.getString("openid");

        // 2. openid存起来？以前是不是存过呢？
        User user = userMapper.selectByOpenid(openid);
        // 2.1 存在，则直接返回 - 返回用户信息
        if (Objects.isNull(user)) {
            // 2.2 不存在，说明用户首次登录，需要重新创建用户
            user = new User();
            user.setOpenid(openid);
            user.setCreateTime(LocalDateTime.now());
            // 主键返回
            userMapper.insert(user);
        }
        // 3. 生成令牌返回
        HashMap<String, Object> map = new HashMap<>(8);
        map.put(JwtClaimsConstant.USER_ID, user.getId());
        String jwt = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), map);

        // 4. 封装 UserLoginVO 返回
        UserLoginVO userLoginVO = new UserLoginVO();
        userLoginVO.setId(user.getId());
        userLoginVO.setOpenid(user.getOpenid());
        userLoginVO.setToken(jwt);
        return userLoginVO;
    }
}
